package com.wude.guild.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.github.shenyuanqing.zxingsimplify.zxing.Activity.CaptureActivity;
import com.mc.developmentkit.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.AppInfo;
import com.wude.bean.NoticeItemData;
import com.wude.bean.TopTu;
import com.wude.guild.GameDetActivity;
import com.wude.guild.ListCouponActivity;
import com.wude.guild.ListTrafficActivity;
import com.wude.guild.LoginActivity;
import com.wude.guild.MainActivity;
import com.wude.guild.ExtractTrafficActivity;
import com.wude.guild.R;
import com.wude.guild.adapter.HomeGameAdapter;
import com.wude.guild.adapter.ImagePagerAdapter;
import com.wude.guild.dialog.CustomProgressDialog;
import com.wude.guild.manager.DownloadnumObserver;
import com.wude.guild.servercore.app.CubeFragment;
import com.wude.guild.views.CircleFlowIndicator;
import com.wude.guild.views.MyListView;
import com.wude.guild.views.ViewFlow;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.Util;
import com.wude.tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/11/22 0022.
 * <p>
 * 首页
 */
@SuppressLint("HandlerLeak")
public class HomeFragment extends CubeFragment implements View.OnClickListener {
    private LinearLayout ll_lingliuliang, ll_liuliang, ll_youhuiq, ll_scan;
    private ViewFlow mViewFlow;
    private CircleFlowIndicator mFlowIndicator;
    private ViewFlipper homepage_notice_vf;
    private LinearLayout ll_message;
    private MyListView listView_hot;
    private TextView tvLiuliang;
    private LinearLayout title;

    private static final int REQUEST_SCAN = 0;
    private List<TopTu> topTuInfos;
    private int mCurrPos;
    private List<NoticeItemData> titleList;
    private static final int MESSAGE_LOGIN = 1;
    private Handler noticeHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == MESSAGE_LOGIN) {
                moveNext();
            }
            return true;
        }
    });
    private Timer timer;
    private HomeGameAdapter homeGameAdapter_hot;
    private List<AppInfo> listGameInfos_hot;

    private String operator = "telecom";//telecom 、unicom 、 all

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);
        initList(2);
    }


    private void initView(View view) {
        ll_lingliuliang = view.findViewById(R.id.ll_lingliuliang);
        ll_liuliang = view.findViewById(R.id.ll_liuliang);
        ll_youhuiq = view.findViewById(R.id.ll_youhuiq);
        ll_scan = findView(view, R.id.ll_scan);
        mViewFlow = findView(view, R.id.viewflow);
        mFlowIndicator = findView(view, R.id.viewflowindic);
        homepage_notice_vf = findView(view, R.id.homepage_notice_vf);
        ll_message = findView(view, R.id.ll_message);
        listView_hot = findView(view, R.id.listView_hot);
        tvLiuliang = findView(view, R.id.tv_liuliang);
        title = findView(view, R.id.title);

        title.setFocusable(true);
        initLunBo();

        homeGameAdapter_hot = new HomeGameAdapter(getActivity());
        listView_hot.setAdapter(homeGameAdapter_hot);
        listView_hot.setOnItemClickListener(onItemClickListener_hot);

        ll_lingliuliang.setOnClickListener(this);
        ll_liuliang.setOnClickListener(this);
        ll_youhuiq.setOnClickListener(this);
        ll_scan.setOnClickListener(this);

        ll_message.setVisibility(View.GONE);
        HttpCom.POST(messageHandler, HttpCom.getGetNotice(), new HashMap<String, String>(), false);
//        progressDialog.show();
    }

    AdapterView.OnItemClickListener onItemClickListener_hot = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent();
            intent.putExtra("id", listGameInfos_hot.get(position).id + "");
            intent.setClass(getActivity(), GameDetActivity.class);
            startActivity(intent);
        }
    };

    /**
     * 获取首页游戏列表
     */
    private void initList(int i) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("recommend", i + "");
        map.put("version", "1");
        switch (i) {
            case 2:         //最热
                HttpCom.POST(hotHandler, HttpCom.getRankingURL(), map, false);
                break;
        }
    }

    /**
     * 热门游戏
     */
    Handler hotHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    listGameInfos_hot = HttpUtils.DNSGameList(msg.obj.toString());
                    if (listGameInfos_hot != null) {
                        homeGameAdapter_hot.setData(listGameInfos_hot);
                        homeGameAdapter_hot.notifyDataSetChanged();
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络错误");
                    break;
            }
        }
    };

    @Override
    public void onResume() {
//        UserInfo info = Utils.getLoginUser();
//        if (info != null && info.all_flow != null) {
//            tvLiuliang.setText(info.all_flow + "M");
//        } else {
//            tvLiuliang.setText("0" + "M");
//        }

        if (homeGameAdapter_hot != null) {
            homeGameAdapter_hot.start();
            homeGameAdapter_hot.State();
        }
        Map<String, String> map = new HashMap<>();
        map.put("token", Utils.getLoginUser() == null ? "" : Utils.getLoginUser().token);
        HttpCom.POST(userHandler, HttpCom.getGetUserInfo(), map, false);
        listView_hot.setFocusable(false);
        super.onResume();
        MobclickAgent.onPageStart("HomeFragment");
    }

    Handler userHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        JSONObject data = jsonObject.getJSONObject("data");
                        String flow = data.getString("flow");
                        tvLiuliang.setText((TextUtils.isEmpty(flow) ? "0" : flow) + "M");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络错误");
                    break;
            }
        }
    };

    @Override
    public void onPause() {
        if (homeGameAdapter_hot != null) {
            homeGameAdapter_hot.delete();
        }
        super.onPause();
        MobclickAgent.onPageEnd("HomeFragment");
    }

    private MainActivity activity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (MainActivity) activity;
    }

    //消息通知设置
    private void moveNext() {
        setNoticeView(mCurrPos, mCurrPos + 1);
        homepage_notice_vf.setInAnimation(activity, R.anim.in_bottomtop);
        homepage_notice_vf.setOutAnimation(activity, R.anim.out_bottomtop);
        homepage_notice_vf.showNext();
    }

    private void setNoticeView(int curr, int next) {
        View noticeItem = LayoutInflater.from(activity).inflate(R.layout.notice_item, null);
        TextView tvNotice = noticeItem.findViewById(R.id.notice_tv);
        if ((curr < next) && (next > (titleList.size() - 1))) {
            next = 0;
        } else if ((curr > next) && (next < 0)) {
            next = titleList.size() - 1;
        }

        tvNotice.setText(titleList.get(next).lottery_name);
        tvNotice.setBackgroundResource(R.color.transparency);

        if (homepage_notice_vf.getChildCount() > 1) {
            homepage_notice_vf.removeViewAt(0);
        }

        homepage_notice_vf.addView(noticeItem, homepage_notice_vf.getChildCount());
        mCurrPos = next;
    }

    //通知消息请求回调
    @SuppressLint("HandlerLeak")
    Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            progressDialog.dismiss();
            switch (msg.what) {
                case 1:
                    titleList = HttpUtils.DNSHomeMessge(msg.obj.toString());
                    if (titleList != null && titleList.size() != 0) {
                        ll_message.setVisibility(View.VISIBLE);

                        TimerTask task = new TimerTask() {
                            @Override
                            public void run() {
                                noticeHandler.sendEmptyMessage(MESSAGE_LOGIN);

                                Log.d("Task", "下一个");
                            }
                        };
                        timer = new Timer();
                        timer.schedule(task, 0, 4000);
                    }
                    break;
                case 2:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
    }

    private void initBanner(ArrayList<String> imageUrlList, List<String> titles) {
        mViewFlow.setAdapter(new ImagePagerAdapter(activity, imageUrlList,
                titles).setInfiniteLoop(true));

        mViewFlow.setmSideBuffer(imageUrlList.size()); // 实际图片张数，
        mViewFlow.setFlowIndicator(mFlowIndicator);
        mViewFlow.setTimeSpan(4000);
        mViewFlow.setSelection(imageUrlList.size() * 1000); // 设置初始位置
        mViewFlow.startAutoFlowTimer(); // 启动自动播放
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_lingliuliang:   //领流量
                if (Utils.getLoginUser() == null) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), ListTrafficActivity.class));
                }
                break;
            case R.id.ll_liuliang://我的流量
                if (Utils.getLoginUser() == null) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), ExtractTrafficActivity.class));
                }
                break;
            case R.id.ll_youhuiq:   //优惠券
                if (Utils.getLoginUser() == null) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), ListCouponActivity.class));
                }
                break;
            case R.id.ll_scan:   //扫一扫
                getPermission();
                break;
        }
    }

    /**
     * 动态请求相机权限
     */
    private void getPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            jumpScanPage();  //跳转到扫码页
        }
    }

    /**
     * 跳转到扫码页
     */
    private void jumpScanPage() {
        startActivityForResult(new Intent(getActivity(), CaptureActivity.class), REQUEST_SCAN);
    }

    /**
     * 获取轮播图数据
     */
    private void initLunBo() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("operator", operator);
        HttpCom.POST(handler, HttpCom.getTopTuURL(), map, false);
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    topTuInfos = HttpUtils.DNSTopTu(msg.obj.toString());
                    if (topTuInfos != null && topTuInfos.size() > 0) {
                        ArrayList<String> dataList = new ArrayList<>();
                        ArrayList<String> titleList = new ArrayList<>();
                        for (int i = 0; i < topTuInfos.size(); i++) {
                            dataList.add(topTuInfos.get(i).url);
                            titleList.add(topTuInfos.get(i).title);
                        }
                        initBanner(dataList, titleList);
                    } else {
                        Log.e("当前没有轮播图广告", "true");
                    }
                    break;
                case 2:
                    break;
            }
        }
    };
}
